package org.alanlau.dynamic.cglib;

import org.alanlau.aspect.MyAspect;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author alan
 * @version 1.0
 * @date 2020/1/12 10:20
 */
public class CglibDynamicProxy implements MethodInterceptor {
    public Object createProxy(Object target) {
        Enhancer enhancer = new Enhancer();
        // 确定要增强的类
        enhancer.setSuperclass(target.getClass());
        // 设置方法拦截器
        enhancer.setCallback(this);
        // 返回创建的代理对象
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        MyAspect myAspect = new MyAspect();
        // 前增强
        myAspect.check();
        myAspect.except();
        // 目标方法执行
        Object obj = methodProxy.invokeSuper(o, args);
        // 后增强
        myAspect.log();
        myAspect.monitor();
        return obj;
    }
}
